/*******************************************************************************
 * Copyright (c) 2004, 2006 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    IBM Corporation - Initial API and implementation
 *******************************************************************************/
package org.eclipse.stp.policy_builder.tcpmonitor.actions;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.stp.policy_builder.tcpmonitor.source.impl.TCPManager;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;
import org.eclipse.wst.internet.monitor.core.internal.provisional.Request;
import org.eclipse.wst.internet.monitor.ui.internal.view.ViewerManager;

public class ExtractPolicyAction implements IViewActionDelegate {
	protected ISelection selection = null;
	protected IViewPart view = null;
	private final static String REQUEST_ACTION_ID = "org.eclipse.wst.internet.monitor.ui.internal.view.ExtractRequestAction";
	private final static String RESPONSE_ACTION_ID = "org.eclipse.wst.internet.monitor.ui.internal.view.ExtractResponseAction";
	private final static int REQUEST_ACTION =1000 ,RESPONSE_ACTION = 1001 ;
	
	public ExtractPolicyAction() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void init(IViewPart v) {
		// TODO Auto-generated method stub
			view = v ;
	}

	@Override
	public void run(IAction action) {
		// TODO Auto-generated method stub
		
		byte[] b = null;
		String str="";
		try{
			if (selection != null) {
				int actionSignal = getAction(action.getId());
				Object element = ((StructuredSelection) selection).getFirstElement();
				
				if (element != null && element instanceof Request) {
					Request req = (Request) element;
					if(REQUEST_ACTION == actionSignal ){
						b = ViewerManager.getRequestContent(req);
					}
					else if(RESPONSE_ACTION == actionSignal){
						b = ViewerManager.getResponseContent(req);
					}
					
				}
			}
			if(b!=null){
				str = new String(b).trim();
				if(!"".equals(str))
					TCPManager.getManager().setMessage(str);
			}
			
			
			System.out.println(": This is the intercepted message : \n"+ str);
		}
		catch(Exception e){
			
		}
	}

	private int  getAction(String id){
		if(REQUEST_ACTION_ID.equals(id)){
			return REQUEST_ACTION ;
		}
		else if (RESPONSE_ACTION_ID.equals(id)){
			return RESPONSE_ACTION ;
		}
				
		return -1 ;
			
	}
	
	@Override
	public void selectionChanged(IAction arg0, ISelection arg1) {
		// TODO Auto-generated method stub
		this.selection = arg1;
		
	}

}
